﻿using System;
using System.IO;
using System.ServiceModel.Activation;
using BackupObjects;
using BackupWebRole.Models;

namespace BackupWebServicesRole
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class BackupWebService : IBackupWebService
    {
        private readonly BackupRepository _backupRepository;

        public BackupWebService()
        {
            _backupRepository = new BackupRepository();
        }

        public BackupEntity LoadById(Guid id, string userName, Credentials credentials)
        {
            AuthentificateUser(credentials);
            return _backupRepository.Load(id, userName);
        }

        public BackupEntity LoadByName(string name, string userName, Credentials credentials)
        {
            AuthentificateUser(credentials);
            return _backupRepository.Load(name, userName);
        }

        public void LoadAll(string userName, Credentials credentials)
        {
            //return _backupRepository.LoadAll(userName);
            throw new NotImplementedException();
        }

        public void Save(BackupEntity backupEntity, Credentials credentials)
        {
            AuthentificateUser(credentials);
            _backupRepository.Save(backupEntity);
        }

        public void Delete(Guid id, string userName, Credentials credentials)
        {
            AuthentificateUser(credentials);
            _backupRepository.Delete(id, userName);
        }

        public Stream GetBackupStream(Guid id, string userName, Credentials credentials)
        {
            AuthentificateUser(credentials);
            return _backupRepository.GetBackupStream(id, userName);
        }

        /// <summary>
        /// Authentificate user based on the given credentials.
        /// </summary>
        /// <param name="credentials">The given credentials.</param>
        private void AuthentificateUser(Credentials credentials)
        {
            IMembershipService membershipService = new AccountMembershipService();

            if (membershipService.ValidateUser(credentials.User, credentials.Password))
            {
                new FormsAuthenticationService().SignIn(credentials.User, false);
            }
        }

    }
}
